package cn.skylark.wcm.init;

import cn.skylark.wcm.common.util.PasswordHelper;
import cn.skylark.wcm.dao.ConstantDao;
import cn.skylark.wcm.dao.ResourcesDao;
import cn.skylark.wcm.dao.RoleDao;
import cn.skylark.wcm.dao.RoleResourcesDao;
import cn.skylark.wcm.dao.TenanDao;
import cn.skylark.wcm.dao.TenanPropertyDao;
import cn.skylark.wcm.dao.UserDao;
import cn.skylark.wcm.dao.UserRoleDao;
import cn.skylark.wcm.entity.Constant;
import cn.skylark.wcm.entity.Resources;
import cn.skylark.wcm.entity.Role;
import cn.skylark.wcm.entity.RoleResources;
import cn.skylark.wcm.entity.Tenan;
import cn.skylark.wcm.entity.Tenanproperty;
import cn.skylark.wcm.entity.User;
import cn.skylark.wcm.entity.UserRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * initConfig
 *
 * @author chuhl
 * @date 2018/1/12
 */
@Component
@Order(value = 3)
public class InitConfig implements CommandLineRunner {
    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger( InitConfig.class );

    /**
     * 权限DAO
     */
    @Autowired
    ResourcesDao resourcesDao;
    /**
     * 角色DAO
     */
    @Autowired
    RoleDao roleDao;
    /**
     * 用户DAO
     */
    @Autowired
    UserDao userDao;
    /**
     * 用户角色DAO
     */
    @Autowired
    UserRoleDao userRoleDao;
    /**
     * 角色权限DAO
     */
    @Autowired
    RoleResourcesDao roleResourcesDao;
    /**
     * 租户DAO
     */
    @Autowired
    TenanDao tenanDao;
    /**
     * 租户属性DAO
     */
    @Autowired
    TenanPropertyDao tenanPropertyDao;
    /**
     * 静态变量表DAO
     */
    @Autowired
    ConstantDao constantDao;

    @Override
    public void run(String... args) throws Exception {
        /**
         * 日志对象
         */
        LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>系统初始化检查及配置开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
        /**
         * 获取权限信息
         */
        List<Resources> resourcesList = resourcesDao.queryAll();
        if (resourcesList == null || resourcesList.size() == 0) {
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>系统初始化开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>权限初始化开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
            initResourcesData( resourcesDao );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>权限初始化结束>>>>>>>>>>>>>>>>>>>>>>>>>" );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>静态变量表初始化开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
            initConstantData( constantDao );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>静态变量表初始化结束>>>>>>>>>>>>>>>>>>>>>>>>>" );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>超级管理员租户初始化开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
            /**
             * 配置超级管理员租户
             */
            Tenan tenan = new Tenan();
            tenan.setTenanname( "北京云雀智享科技有限公司" );
            tenan.setDelflg( 0 );
            tenan.setStorage( new Long(900000000) );
            tenan.setTenancode( "yqzx" );
            tenanDao.insert( tenan );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>超级管理员租户初始化结束>>>>>>>>>>>>>>>>>>>>>>>>>" );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>超级管理员租户属性初始化开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
            Tenan selectTenant = initTenanpropertyData( tenanDao, tenan, tenanPropertyDao );
            Integer tenanid = selectTenant.getId();
            String tenancode = selectTenant.getTenancode();
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>超级管理员租户属性初始化结束>>>>>>>>>>>>>>>>>>>>>>>>>" );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>超级管理员用户初始化开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
            /**
             * 配置超级管理员用户
             */
            PasswordHelper passwordHelper = new PasswordHelper();
            User user = new User();
            user.setTenanid( tenanid );
            user.setUsername( tenancode );
            user.setPassword( passwordHelper.encrypt( tenancode ) );
            user.setDelflg( 0 );
            user.setEnable( 0 );
            user.setSex( 0 );
            userDao.insert( user );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>超级管理员用户初始化结束>>>>>>>>>>>>>>>>>>>>>>>>>" );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>角色初始化开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
            /**
             * 配置角色
             */
            Role role = new Role();
            role.setTenanid( tenanid );
            role.setDelflg( 0 );
            role.setType( 1 );
            role.setRoledesc( "超级管理员" );
            roleDao.insert( role );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>角色初始化结束>>>>>>>>>>>>>>>>>>>>>>>>>" );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>角色权限初始化开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
            /**
             * 配置角色权限
             */
            List<Resources> selectResources = resourcesDao.selectAll();
            Role selectRole = roleDao.selectOne( role );
            List<RoleResources> roleResourcesList = new ArrayList<RoleResources>();
            for (Resources resources : selectResources) {
                RoleResources roleResources = new RoleResources();
                roleResources.setDelflg( 0 );
                roleResources.setResourcesid( String.valueOf( resources.getId() ) );
                roleResources.setRoleid( selectRole.getId() );
                roleResourcesList.add( roleResources );
            }
            roleResourcesDao.insertList( roleResourcesList );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>角色权限初始化结束>>>>>>>>>>>>>>>>>>>>>>>>>" );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>用户角色初始化开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
            /**
             * 配置用户角色
             */
            User selectUser = userDao.selectOne( user );
            UserRole userRole = new UserRole();
            userRole.setUserid( selectUser.getId() );
            userRole.setRoleid( String.valueOf( selectRole.getId() ) );
            userRole.setDelflg( 0 );
            userRoleDao.insert( userRole );
            selectTenant.setUserid( selectUser.getId() );
            tenanDao.updateByPrimaryKey( selectTenant );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>用户角色初始化开始>>>>>>>>>>>>>>>>>>>>>>>>>" );
            LOGGER.info( ">>>>>>>>>>>>>>>>>>>>>>>>>系统初始化结束>>>>>>>>>>>>>>>>>>>>>>>>>" );
        } else {
            LOGGER.info( "<<<<<<<<<<<<<<<<<<<<<<<<<系统已经初始化<<<<<<<<<<<<<<<<<<<<<<<<<" );
        }
        LOGGER.info( "<<<<<<<<<<<<<<<<<<<<<<<<<系统初始化检查及配置结束<<<<<<<<<<<<<<<<<<<<<<<<<" );
    }

    /**
     * 权限数据初始化
     *
     * @param resourcesDao 权限Dao
     */
    private static void initResourcesData(ResourcesDao resourcesDao) {
        /**
         * 配置权限信息
         */
        List<String> resourcesArr = new ArrayList<String>();
        //字符串定义标识（name【权限名称】,resurl【权限标识路径】,delflg【删除标识】,sort【排序】,type【1：菜单，2：按钮】,parentid【默认父类为0】）
        resourcesArr.add(" 登录,/login,0,2,2,0");
        resourcesArr.add(" 网页管理,/webmanager,0,2,0,0");
        resourcesArr.add(" 网页管理_文档,/pagemanager,0,2,1,2");
        resourcesArr.add(" 文件管理,/papers,0,2,0,0");
        resourcesArr.add(" 文件管理_文档,/filemanager,0,2,1,4");
        resourcesArr.add(" 文件管理_视频,/video,0,2,1,4");
        resourcesArr.add(" 回收站,/trash,0,2,0,0");
        resourcesArr.add(" 回收站_回收站,/recycle,0,2,1,7");
        resourcesArr.add(" 用户管理,/usersystem,0,1,0,0");
        resourcesArr.add(" 用户管理_租户管理,/tenans,0,1,1,9");
        resourcesArr.add(" 用户管理_用户管理,/users,0,1,1,9");
        resourcesArr.add(" 用户管理_角色管理,/roles,0,1,1,9");
        resourcesArr.add(" 用户管理_权限管理,/resources,0,1,1,9");
        resourcesArr.add(" 个人资料,/personinfo,0,2,0,0");
        resourcesArr.add(" 个人资料_个人信息,/userinfo,0,2,1,14");
        resourcesArr.add(" 个人资料_修改密码,/userpwd,0,2,1,14");
        resourcesArr.add(" 文件管理_文档_初始,/filemanager/selectInitFileListByParameter,0,2,2,5");
        resourcesArr.add(" 文件管理_文档_上传,/filemanager/upload,0,2,2,5");
        resourcesArr.add(" 文件管理_文档_新建文件夹,/filemanager/saveFolder,0,2,2,5");
        resourcesArr.add(" 文件管理_文档_删除,/filemanager/delete,0,2,2,5");
        resourcesArr.add(" 文件管理_文档_批量删除,/filemanager/batchDelete,0,2,2,5");
        resourcesArr.add(" 文件管理_文档_文件夹详情,/filemanager/selectByPageFolder,0,2,2,5");
        resourcesArr.add(" 文件管理_文档_返回上一级,/filemanager/backoff,0,2,2,5");
        resourcesArr.add(" 文件管理_文档_转换,/filemanager/convertFile,0,2,2,5");
        resourcesArr.add(" 文件管理_视频_初始,/filemanager/selectVideoListByParameter,0,2,2,6");
        resourcesArr.add(" 文件管理_视频_上传,/filemanager/uploadVideo,0,2,2,6");
        resourcesArr.add(" 文件管理_视频_删除,/filemanager/delete,0,2,2,6");
        resourcesArr.add(" 文件管理_视频_批量删除,/filemanager/batchDelete,0,2,2,6");
        resourcesArr.add(" 网页管理_文档_初始,/pagemanager/getHtmlFile,0,2,2,3");
        resourcesArr.add(" 网页管理_文档_上传,/pagemanager/uploadHTMLFile,0,2,2,3");
        resourcesArr.add(" 网页管理_文档_新建文件夹,/pagemanager/saveFolder,0,2,2,3");
        resourcesArr.add(" 网页管理_文档_新建HTML,/pagemanager/uploadHTML,0,2,2,3");
        resourcesArr.add(" 网页管理_文档_删除,/pagemanager/deleteHtml,0,2,2,3");
        resourcesArr.add(" 网页管理_文档_批量删除,/pagemanager/batchDelete,0,2,2,3");
        resourcesArr.add(" 网页管理_文档_文件夹详情,/pagemanager/getHtmlFolder,0,2,2,3");
        resourcesArr.add(" 网页管理_文档_返回上一级,/pagemanager/backoff,0,2,2,3");
        resourcesArr.add(" 网页管理_文档_编辑,/pagemanager/getHtmlContent,0,2,2,3");
        resourcesArr.add(" 网页管理_文档_浏览,/pagemanager/previewHtml,0,2,2,3");
        resourcesArr.add(" 回收站_回收站_初始,/recycle/getDeleteFile,0,2,2,8");
        resourcesArr.add(" 回收站_回收站_文件夹详情,/recycle/getDeleteFileFolder,0,2,2,8");
        resourcesArr.add(" 回收站_回收站_彻底删除,/recycle/deleteFileThorough,0,2,2,8");
        resourcesArr.add(" 回收站_回收站_清空回收站,/recycle/deleteAllFileThorough,0,2,2,8");
        resourcesArr.add(" 回收站_回收站_恢复文件,/recycle/recoveryFilePrompt,0,2,2,8");
        resourcesArr.add(" 回收站_回收站_恢复文件（重名）,/recycle/recoveryFile,0,2,2,8");
        resourcesArr.add(" 回收站_回收站_返回上一级,/recycle/backoff,0,2,2,8");
        resourcesArr.add(" 用户管理_租户管理_初始,/tenans/getAllTenan,0,1,2,10");
        resourcesArr.add(" 用户管理_租户管理_新增,/tenans/addTenan,0,0,2,10");
        resourcesArr.add(" 用户管理_租户管理_删除,/tenans/deleteTenan,0,0,2,10");
        resourcesArr.add(" 用户管理_租户管理_设置属性初始,/tenanproperty/gettenanProperty,0,1,2,10");
        resourcesArr.add(" 用户管理_租户管理_设置属性保存,/tenanproperty/saveTenanProperty,0,1,2,10");
        resourcesArr.add(" 用户管理_用户管理_初始,/users/getAllUserByTenanid,0,1,2,11");
        resourcesArr.add(" 用户管理_用户管理_新增,/users/add,0,1,2,11");
        resourcesArr.add(" 用户管理_用户管理_删除,/users/delete,0,1,2,11");
        resourcesArr.add(" 用户管理_用户管理_恢复冻结,/users/updatestate,0,1,2,11");
        resourcesArr.add(" 用户管理_用户管理_分配角色初始,/userrole/getAllRoleByTenanid,0,1,2,11");
        resourcesArr.add(" 用户管理_用户管理_分配角色保存,/userrole/addRole,0,1,2,11");
        resourcesArr.add(" 用户管理_角色管理_初始,/roles/getRolesByTenanId,0,1,2,12");
        resourcesArr.add(" 用户管理_角色管理_新增,/roles/add,0,1,2,12");
        resourcesArr.add(" 用户管理_角色管理_删除,/roles/delete,0,1,2,12");
        resourcesArr.add(" 用户管理_角色管理_分配权限初始,/roles/getAllResourceWithTenanId,0,1,2,12");
        resourcesArr.add(" 用户管理_角色管理_分配权限保存,/roles/saveRoleResources,0,1,2,12");
        resourcesArr.add(" 用户管理_权限管理_初始,/resources/getResourcesListByUserid,0,1,2,13");
        resourcesArr.add(" 用户管理_权限管理_删除,/resources/logicDelete,0,0,2,13");
        resourcesArr.add(" 个人资料_个人信息_初始,/users/getUserData,0,2,2,15");
        resourcesArr.add(" 个人资料_个人信息_确定,/users/saveUserData,0,2,2,15");
        resourcesArr.add(" 个人资料_修改密码_确定,/users/updatePassword,0,2,2,16");

        /**
         * 生成权限对象集合
         */
        List<Resources> resourcesList = new ArrayList<Resources>();
        for (String resourceStr : resourcesArr) {
            Resources resources = new Resources();
            String[] tmparr = resourceStr.split( "," );
            resources.setName( tmparr[0] );
            resources.setResurl( tmparr[1] );
            resources.setDelflg( Integer.valueOf( tmparr[2] ) );
            resources.setSort( Integer.valueOf( tmparr[3] ) );
            resources.setType( Integer.valueOf( tmparr[4] ) );
            resources.setParentid( Integer.valueOf( tmparr[5] ) );
            resourcesList.add( resources );
        }
        resourcesDao.insertList( resourcesList );
    }

    /**
     * 静态变量初始化
     *
     * @param constantDao 静态变量表DAO
     */
    private static void initConstantData(ConstantDao constantDao) {
        /**
         * 配置静态变量表
         */
        List<String> constantArr = new ArrayList<String>();
        //字符串定义标识（groupid【分组id】,keycode【键CODE】,keyname【键名称】,delflg【删除标识0：未删除，1：删除】）
        constantArr.add( "1,AppId,存储桶appid,0" );
        constantArr.add( "1,SecretId,存储桶secretid,0" );
        constantArr.add( "1,SecretKey,存储桶secretkey,0" );
        constantArr.add( "1,Region,存储桶区域,0" );
        constantArr.add( "1,BucketName,存储桶名称,0" );
        constantArr.add( "2,TenanWechatApiId,租户微信api账号id,0" );
        constantArr.add( "2,TenanWechatApiPwd,租户微信api账号密码,0" );
        constantArr.add( "2,TenanWebApiId,租户webapi账号id,0" );
        constantArr.add( "2,TenanWebApiPwd,租户webapi账号密码,0" );
        constantArr.add( "3,WechatAppid,微信appid,0" );
        constantArr.add( "3,WechatAppsecret,微信secret,0" );
        constantArr.add( "3,WechatToken,微信Token,0" );
        constantArr.add( "3,WechatAESKey,微信AESKEY,0" );
        constantArr.add( "3,WechatCode,微信号,0" );
        /**
         * 生成静态变量表
         */
        List<Constant> constantList = new ArrayList<Constant>();
        for (String constantStr : constantArr) {
            Constant constant = new Constant();
            String[] tmpArr = constantStr.split( "," );
            constant.setGroupid( Integer.valueOf( tmpArr[0] ) );
            constant.setKeycode( tmpArr[1] );
            constant.setKeyname( tmpArr[2] );
            constant.setDelflg( Integer.valueOf( tmpArr[3] ) );
            constantList.add( constant );
        }
        constantDao.insertList( constantList );
    }

    /**
     * 租户属性初始化
     *
     * @param tenanDao         租户DAO
     * @param tenan            租户实体
     * @param tenanPropertyDao 租户属性DAO
     * @return
     */
    private Tenan initTenanpropertyData(TenanDao tenanDao, Tenan tenan, TenanPropertyDao tenanPropertyDao) {
        /**
         * 配置租户属性
         */
        Tenan selectTenant = tenanDao.selectOne( tenan );
        List<String> tenanpropertyArr = new ArrayList<String>();
        //字符串定义标识（tenanid,tenancode,keycode,keyvalue,delflg）
        Integer tenanid = selectTenant.getId();
        String tenancode = selectTenant.getTenancode();
        tenanpropertyArr.add( tenanid + "," + tenancode + ",AppId,1253363526,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",SecretId,AKIDOflARZCHtaK944m80iFalkYAbrvoH2NW,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",SecretKey,98wZ2KivwnSxGPM7h6KMD2hBUQHxSlur,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",Region,gz,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",BucketName,publictest,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",TenanWechatApiId,,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",TenanWechatApiPwd,,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",TenanWebApiId,,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",TenanWebApiPwd,,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",WechatAppid,,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",WechatAppsecret,,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",WechatToken,,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",WechatAESKey,,0" );
        tenanpropertyArr.add( tenanid + "," + tenancode + ",WechatCode,,0" );
        List<Tenanproperty> tenanpropertyList = new ArrayList<Tenanproperty>();
        for (String tenanpropertyStr : tenanpropertyArr) {
            Tenanproperty tenanproperty = new Tenanproperty();
            String[] tmpArr = tenanpropertyStr.split( "," );
            tenanproperty.setTenanid( Integer.valueOf( tmpArr[0] ) );
            tenanproperty.setTenancode( tmpArr[1] );
            tenanproperty.setKeycode( tmpArr[2] );
            tenanproperty.setKeyvalue( tmpArr[3] );
            tenanproperty.setDelflg( Integer.valueOf( tmpArr[4] ) );
            tenanpropertyList.add( tenanproperty );
        }
        tenanPropertyDao.insertList( tenanpropertyList );
        return selectTenant;
    }
}
